package defaulter

import (
	"bufio"
	"os"
	"strings"

	"gitee.com/haodreams/golib/autoroute/controller"
	"gitee.com/haodreams/golib/logs/httplog"
)

//LogController 授权相关的操作
type LogController struct {
	controller.AuthController
}

//Index 注册
func (m *LogController) Index() {
	if m.IsPost() {
		httplog.HTTPLogs(m.Writer, m.Request)
		return
	}
	m.Display()
}

type log struct {
	Time string `json:"time"`
	File string `json:"caller"`
	Msg  string `json:"message"`
}

//Init 启动日志
func (m *LogController) Init() {
	if m.IsPost() {
		page, limit := m.GetPage()
		begin := (page - 1) * limit
		end := page * limit
		f, err := os.Open("logs/init.log")
		if err != nil {
			return
		}
		defer f.Close()
		buf := bufio.NewReader(f)
		idx := 0
		i := 0
		num := end - begin
		if num < 0 {
			num = 0
		}
		rows := make([]*log, num)
		for line, err := buf.ReadString(3); err == nil || len(line) > 0; line, err = buf.ReadString(3) {
			if idx >= begin && idx < end {
				if len(line) > 0 {
					line = line[:len(line)-1]
				}
				ss := strings.SplitN(line, " ", 4)
				if len(ss) < 4 {
					continue
				}
				l := new(log)
				l.Time = ss[0] + " " + ss[1]
				l.File = ss[2]
				l.Msg = ss[3]
				rows[i] = l
				i++
			}
			idx++
		}
		if idx == 0 {
			m.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
			m.Writer.Write([]byte(`{"code":200,"count":0,"data":[]}`))
			return
		}
		m.Rows(idx, rows, "OK")
		return
	}
	m.Display()
}
